package com.zktr.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.zktr.bean.GoodsBean;
import com.zktr.pojo.Goods;
import com.zktr.pojo.OrderInfo;
import com.zktr.pojo.OrderInfoBean;
import com.zktr.pojo.PageBean;
import com.zktr.service.CategoryService;
import com.zktr.service.GoodsService;

/**
 * @author yf  
 * @version 创建时间：2018年8月29日  上午12:01:40
 * tags
 */
@WebServlet("/GoodsServlet")
public class GoodsServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	GoodsService GService=new GoodsService();
	/**
	 * 查询所有商品
	 * @param req
	 * @param res
	 * @throws IOException
	 */
	public void quaryAllGoods(HttpServletRequest req,HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		int pc = getPc(req);
		int ps = 15;
		PageBean<GoodsBean> pageBean = GService.findAllGoods(pc, ps);
		pageBean.setUrl(getUrl(req));
		req.getSession().setAttribute("pageBean",pageBean.getBeanList() );
		req.getSession().setAttribute("pb",pageBean);
		out.println("0");
	}
	
	private int getPc(HttpServletRequest req) {
		String value = req.getParameter("pc");
		if(value == null || value.trim().isEmpty()) {
			return 1;
		}
		try{
			return Integer.parseInt(value);
		}catch(Exception e){
			return  1;
		}
	}
	/**
	 * 按分类id分页查询所有商品
	 * @return 
	 */
	public PageBean<Goods> queryByCategoryAll(HttpServletRequest req,int catid){
		int pc=getPc(req);
		int ps=10;
		PageBean<Goods> pagebean = GService.queryByCategoryAll(catid, pc, ps);
		pagebean.setUrl(getUrl(req));
		return pagebean;
	}
	private String getUrl(HttpServletRequest request) {
		String contextPath = request.getContextPath();
		String servletPath = request.getServletPath();
		String queryString = request.getQueryString();
		if(queryString.contains("&pc=")) {
			int index = queryString.lastIndexOf("&pc=");
			queryString = queryString.substring(0, index);
		}
		return contextPath + servletPath + "?" + queryString;
	}
	/**更新商品信息
	 * @param req
	 * @param res
	 * @throws IOException
	 */
	public void updateAllGoods(HttpServletRequest req,HttpServletResponse res) throws IOException{
		PrintWriter out = res.getWriter();
		Goods goods = new Goods();
		goods.setGoodssn(req.getParameter("goodssn"));
		goods.setKeywords(req.getParameter("goodsname"));
		double marketprice=Double.parseDouble(req.getParameter("marketprice"));
		goods.setMarketprice(BigDecimal.valueOf(marketprice));
		goods.setGoodsnumber(Integer.parseInt(req.getParameter("goodsnumber")));
		if (req.getParameter("isnew")=="否") {
			goods.setIsnew(false);
		}else {
			goods.setIsnew(true);
		}
		if (req.getParameter("ishot")=="否") {
			goods.setIshot(false);
		}else {
			goods.setIshot(true);
		}
		goods.setGiveintegral(Integer.parseInt(req.getParameter("giveintegral")));
       int row = GService.updateGoods(goods, Integer.parseInt(req.getParameter("goodsid")));
       System.out.println(row);
        out.print("1");
	}
	
	/**
	 * 根据id删除商品信息
	 * @param req
	 * @param res
	 * @throws IOException
	 */
	public void deleteOneGoods(HttpServletRequest req,HttpServletResponse res) throws IOException{
		PrintWriter out = res.getWriter();
        String id = req.getParameter("goodsid");
        int row=GService.deleteOneGoods(Integer.parseInt(id));
        if (row==0) {
			out.print("1");
		}else {
			 out.print("0");
		}
       
	}
	
	/**
	 * 根据id查询商品信息
	 * @param req
	 * @param res
	 * @throws IOException
	 */
	public void queryOneGoods(HttpServletRequest req,HttpServletResponse res) throws IOException{
		PrintWriter out = res.getWriter();
        String id = req.getParameter("goodsid");
        System.out.println(id);
        List<GoodsBean> gBeans=GService.queryOneGoods(Integer.parseInt(id));
        System.out.println(gBeans);
        HttpSession session = req.getSession();
        session.setAttribute("list", gBeans);
        out.print("0");
       
	}
	
	public void addAllGoods(HttpServletRequest req,HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();

		out.println("0");
	}
	public void comment(HttpServletRequest req,HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();

		out.println("0");
	}
	public void addNewGoods(HttpServletRequest req,HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		Goods goods = new Goods();
		int num=(int)(20+Math.random()*(100-20+1));
		GoodsService gService = new GoodsService();
		goods.setGoodsid(num);
		goods.setGoodssn(req.getParameter("goodssn"));
		goods.setGoodsname(req.getParameter("goodsname"));
		double marketprice=Double.parseDouble(req.getParameter("marketprice"));
		goods.setMarketprice(BigDecimal.valueOf(marketprice));
		goods.setCatid(Integer.parseInt(req.getParameter("catid")));
		goods.setBrandid(Integer.parseInt(req.getParameter("brandid")));
		goods.setGoodsimg(req.getParameter("goodsimg"));
		goods.setIntegral(Integer.parseInt(req.getParameter("integral")));
		goods.setGiveintegral(Integer.parseInt(req.getParameter("giveintegral")));
			goods.setGoodsnumber(num);
			goods.setIsnew(true);
			goods.setIshot(true);
			goods.setTypeid(5);
			goods.setKeywords("手");
		    goods.setIsdelete(false);
	
        int row = gService.addNewGoods((goods));

        if (row==1) {
        	 out.print("0");
		}else {
			 out.print("1");
		}
       
	}
	public void dateimport(HttpServletRequest req,HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		out.println("0");
	}
	public void enterimport(HttpServletRequest req,HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		out.println("0");
	}
	public void updataimage(HttpServletRequest req,HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();

		out.println("0");
	}
	/**
	 * 验证分类名是否存在
	 * @param req
	 * @param res
	 * @throws IOException
	 * @throws ServletException
	 */
	public void fileEnter(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException {
				PrintWriter out = res.getWriter();
				CategoryService cService = new CategoryService();
				String stuname = req.getParameter("cate");
				Boolean fileaddress = cService.selectCateGoods(stuname);
				if (fileaddress) {
					out.print("0");
				}else {
					out.print("1");
				}
				
		
	}
	/**
	 * 文件批量上传
	 * @param req
	 * @param res
	 * @throws Exception
	 */
	public void fileEnters(HttpServletRequest req,HttpServletResponse res) throws Exception  {
		CategoryService cService = new CategoryService();
		PrintWriter out = res.getWriter();
		System.out.println(req.getParameter("cate"));
		SmartUpload smartUpload = new SmartUpload();
		String stuname = smartUpload.getRequest().getParameter("cate");
		Boolean fileaddress = cService.selectCateGoods(stuname);
		System.out.println(fileaddress);
		ServletConfig config = this.getServletConfig();
		smartUpload.initialize(config, req, res);
		try {
			smartUpload.upload();
			com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0);
			String name = smartFile.getFilePathName();
			String path= req.getSession().getServletContext().getRealPath("/GoodsServlet");
		    String replaceAll = path.replaceAll("GoodsServlet", "myFiles");
			String address=replaceAll +"\\"+ name;
			smartFile.saveAs(address);
			String endress=address.replaceAll("\\\\", "/");
		 GService.testFileUpdate(endress);
		} catch (SmartUploadException e) {
			e.printStackTrace();
		}
		out.print("0");
	

}
	/**
	 * 处理get请求的中文编码
	 * @param request 
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	private Goods encoding(HttpServletRequest request)  {
		String goodsid=request.getParameter("gid");
		String goodsname=request.getParameter("gname");
		Goods goods=new Goods();
		if(goodsid != null && !goodsid.trim().isEmpty()) {
			goods.setGoodsid(Integer.valueOf(goodsid));
		}
		if( goodsname != null && ! goodsname.trim().isEmpty()) {
			goods.setGoodsname(goodsname);
			
		}
		return goods;
	}
	/**
	 * 分页查询按条件得到结果：
	 */
	protected void  findAllGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		 Goods info = encoding(request);
		int pc = getPc(request);
		int ps =10;	
		PageBean<GoodsBean> pageBean =GService.findGoods(info,pc, ps);//传递pc, ps给Service，得到PageBean
		pageBean.setUrl(getUrl(request));
		request.getSession().setAttribute("pageBean",pageBean.getBeanList() );
		request.getSession().setAttribute("pb",pageBean);
		out.println("0");
	}
}